//
//  TRUserhomeViewController.m
//  WeiMiLan
//
//  Created by anan on 14/11/16.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRUserhomeViewController.h"
#import "TRHomeSearchController.h"

@interface TRUserhomeViewController ()
@property (nonatomic,strong) TRHomeSearchController *searchVC;
@end

@implementation TRUserhomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.contents = [[NSMutableArray alloc] init];
    [self initNavigation];
    
    self.userhomeHeaderView = [[[NSBundle mainBundle] loadNibNamed:@"TRUserhomeHeaderView" owner:self options:nil] lastObject];
    self.searchVC.searchBar.delegate = self;
    //[self.viewContent addSubview:self.userhomeHeaderView];

    [self updateUserInfo];
    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.searchVC = [[TRHomeSearchController alloc]init];
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr{
    [self.searchVC.searchBar resignFirstResponder];
}

- (void)updateUserInfo
{
    [QLMaskUtil showMaskLoadingWithView:self.userhomeHeaderView];
    
    [[QLUserManager shareInstance] detailWithUserId:self.userId callback:^(BOOL isCache, id data) {
        [QLMaskUtil hideLoadingMaskWithView:self.userhomeHeaderView];
        if (data) {
            NSDictionary *userInfo = data;
            self.userhomeHeaderView.userInfo = userInfo;
            
            self.weChatNavigationBar.titleLabel.text=userInfo[@"NAME"];
        }
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.collectionView==nil) {
        [self initCollectionView];
    }
    self.userhomeHeaderView.viewController = self;
}

- (void)initCollectionView
{
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.headerHeight = 127;
    layout.footerHeight = 0;
//    layout.minimumColumnSpacing = 10;
//    layout.minimumInteritemSpacing = 10;
    
    CGRect frame = CGRectMake(
                             0,
                             0,
                             self.viewContent.frame.size.width,
                             self.viewContent.frame.size.height);
    self.collectionView=[[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
    layout.columnCount = 1;
    self.collectionView.delegate = self;
    self.collectionView.alwaysBounceVertical = YES;
    self.collectionView.dataSource = self;
    [self.viewContent insertSubview:self.collectionView atIndex:0];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"TRMemuCell" bundle:nil] forCellWithReuseIdentifier:@"TRMemuCell"];
    [self.collectionView addSubview:self.userhomeHeaderView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self addHeader];
    [self addFooter];
    
    [self performSelector:@selector(refreshF) withObject:nil afterDelay:0.5];
}

- (void)refreshF
{
    [refreshHeaderView beginRefreshing];
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"";
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(exit) forControlEvents:UIControlEventTouchUpInside];
//    self.weChatNavigationBar.rightButton.width=44;
//    self.weChatNavigationBar.rightButton.titleLabel.font = [UIFont systemFontOfSize:14];
//    [self.weChatNavigationBar.rightButton setTitle:@"分享" forState:UIControlStateNormal];
//    [self.weChatNavigationBar.rightButton setImage:nil forState:0];
//    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(buttonShareAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.weChatNavigationBar.rightButton setImage:[UIImage imageNamed:@"seachBT"] forState:0];
    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.rightButton.frame=CGRectMake(kUI_SCREEN_WIDTH-46, 30, 23, 23);
}

- (void)search:(id)sender
{
  //  [self.navigationController pushViewController:self.searchVC animated:YES];
   // [self.userhomeHeaderView buttonShareAction:nil];
 //   [self addChildViewController:self.searchVC];
  [self presentViewController:self.searchVC animated:YES completion:nil];
    
//    UIViewController * vc = [[UIViewController alloc] init];
//    vc.view.backgroundColor = [UIColor blueColor];
//    //  self.hidesBottomBarWhenPushed = YES;
//    //   self.tabBarController.tabBar.hidden =  YES;
//    [self presentViewController:vc animated:YES completion:nil];
}

-(void)exit
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)removeTopButton{
    
}

-(void)visibleTop{
    
}

- (void)loadData:(int)num
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:QLIntToNumber(num) forKey:@"PAGE_NUM"];
    [dic ql_setInterge:self.userId forKey:@"userId"];
    
    NSString* keyWord = self.searchVC.searchBar.text;
    if (keyWord&&keyWord.length>0) {
        [dic ql_setObject:keyWord forKey:@"NAME"];
    }
    
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:@"http://ping.vsmu.cn/app/Interface/Package?ORDER_DIRECTION=0&ORDER_FIELD=createDate&type=1016" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
            if (num==1) {
                //第一页
                if ([responseObject[@"PACKAGE_RSP"][@"PACKAGE"] isKindOfClass:[NSDictionary class]]) {
                    [self.contents addObject:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
                }else{
                    self.contents = [NSMutableArray arrayWithArray:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
                }
            }else{
                [self.contents addObjectsFromArray:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
            }
            
            NSDictionary *pageInfo = responseObject[@"PAGE_INFO"];
            self.nextPage = [pageInfo ql_intForKey:@"NEXT"];
            self.currentPage = [pageInfo ql_intForKey:@"NUMBER"];
            if (self.nextPage>self.currentPage) {
                refreshFooterView.isend = NO;
            }else{
                refreshFooterView.isend = YES;
            }
            
            [self performSelector:@selector(doneWithView:) withObject:nil afterDelay:0.2f];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:STR_MSG_NETWORK_ERROR];
        [self performSelector:@selector(doneWithView:) withObject:nil afterDelay:0.2f];
    }];
}


- (void)addFooter
{
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.collectionView;
    refreshFooterView = footer;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self loadData:self.nextPage];
    };
}

- (void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.collectionView;
    refreshHeaderView = header;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self loadData:1];
    };
}

- (void)doneWithView:(id)sender
{
    // 刷新表格
    [refreshFooterView endRefreshing];
    [refreshHeaderView endRefreshing];
    [self.collectionView reloadData];
}

#pragma mark - QLMaskNodataViewOnClickDelegate
-(void)onClick:(id)sender
{
    [QLMaskUtil hideNodataMaskWithView:self.collectionView];
    [refreshHeaderView beginRefreshing];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.contents==nil?0:self.contents.count;
   // return 5;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSArray * goods = self.contents;
    TRMemuCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"TRMemuCell" forIndexPath:indexPath];
    if (goods.count>indexPath.row) {
        if (indexPath.row==goods.count-1) {
            [collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
        }
        cell.tag=indexPath.row;
        cell.info = goods[indexPath.row];
        
    }
    return cell;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:NO];
    NSDictionary *dic = [self.contents objectAtIndex:indexPath.row];
    [QLPlayerManager openProductDetailWithId:[dic ql_stringForKey:@"ID"] viewController:self];}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSArray * goods = self.contents;
    TRMemuCell *cell =[[TRMemuCell alloc] init];
    cell.info = [goods objectAtIndex:indexPath.row];
    return [cell getSize];
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 2;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 2;
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.searchVC.searchBar resignFirstResponder];
    NSString* keyWord = self.searchVC.searchBar.text;
    if (keyWord&&keyWord.length>0) {
        [refreshHeaderView beginRefreshing];
    }
}

@end

